package com.topera.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.topera.eduservice.entity.EduChapter;
import com.topera.eduservice.entity.EduVideo;
import com.topera.eduservice.mapper.EduChapterMapper;
import com.topera.eduservice.service.EduChapterService;
import com.topera.eduservice.service.EduVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author puzhenjiang
 * @since 2020-05-18
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService eduVideoService;

    @Override
    public List<EduChapter> getAllChapterBycourseId(String courseId) {

        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        List<EduChapter> chapterList = baseMapper.selectList(wrapper);

        //递归查询子节点信息
        getChildNodes(chapterList);

        return chapterList;
    }

    @Override
    public void removeChapterByCourseId(String id) {
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",id);
        baseMapper.delete(wrapper);
    }

    /**
     * 递归查询子节点信息
     * @param chapterList
     * @return
     */
    private List<EduChapter> getChildNodes(List<EduChapter> chapterList){

        chapterList.stream().forEach((chapter)->{
            QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
            wrapper.eq("course_id",chapter.getCourseId());
            wrapper.eq("chapter_id",chapter.getId());
            wrapper.orderByDesc("sort");
            List<EduVideo> videoList =  eduVideoService.list(wrapper);
            chapter.setChildren(videoList);
        });

        return chapterList;
    }
}
